﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class create_city_s : System.Web.UI.Page
{

    int no,no1;
    int type;
    ctpDataContext db;

    protected void Page_Load(object sender, EventArgs e)
    {
        //init helper class
        GeoLingManager glManager = new GeoLingManager(Request, Response);
        String _lang = glManager.getLang();
        DatabaseUtil dbUtil = new DatabaseUtil();
        //Get user's preferred langugage in int
        _lang = dbUtil.getLanguageNo(_lang).ToString();
        ArrayList al = new ArrayList();
 
        string backurl;

        if (Request["no"] != null)
        {
           backurl = "create_city_s.aspx?no=" + Request["no"];
        }
        else
            backurl = "create_city_s.aspx?no1=" + Request["no1"];

        ctp_lib.check_login(this.Page, backurl);

        db = new ctpDataContext();


        int check_userno = (int)Session["userno"];
        
        
        var datacheck = from p in db.ct_s_profiles
                        where p.create_user_no == check_userno
                        orderby p.c_time descending
                        select p;

        if (datacheck.Count() != 0)
        {
            ct_s_profile check_ct_s = datacheck.First();

            DateTime check_time = check_ct_s.c_time;
            TimeSpan check_span = DateTime.Now - check_time;

            if (check_span.TotalSeconds < 30)
            {
                //Response.Write("error");
                this.Page.Visible = false;
                return;
            }

        }





        if (!this.IsPostBack)
        {
            //var type_data = from p in db.ct_s_types
             //               where p.no <= 7
             //               select p;
            var type_data = from p in db.ct_s_types
                            select p;
            this.RadioButtonList1.DataSource = type_data;
            this.RadioButtonList1.DataTextField = "title";
            this.RadioButtonList1.DataValueField = "no";


            this.RadioButtonList1.DataBind();
            this.Panel2.Visible = false;
        }

        if (Request["no"] != null)
        {
            no = int.Parse(Request["no"]);
            type = 0;

        }
        else
        {
            type = 1;
            no1 = int.Parse(Request["no1"]);

            
            ct_s_profile cts = db.ct_s_profiles.Single(p =>p.valid==true&& p.no ==no1 && p.language_no == (int)Session["now_user_lang_no"]);
            no = (int)cts.ct_no;

            if (!this.IsPostBack)
            {
                ListItem li = this.RadioButtonList1.Items.FindByValue(cts.type_no.ToString());
                if (li != null)
                {
                    li.Selected = true;
                }
                int[] post_nos = { cts.no };
                Hashtable table = dbUtil.getTranlatePosts((int)DatabaseUtil.fromTables.s_profile_title, post_nos);
            
                String title = dbUtil.getPropertyPost(cts.title.Trim(), table, cts.no, _lang);
                this.anchor_original_text.InnerText = dbUtil.getOriginalPost(cts.title, table, cts.no);
                this.TextBox1.Text = title;
                this.TextBox2.Text = cts.profile;
            }



            this.Label8.Visible = false;
            this.TextBox3.Visible= false;

            this.bindall();

            
        }


        if (!this.IsPostBack)
        {
            ct_profile city = db.ct_profiles.Single(p=>p.no==no && p.language_no==0 );
            //this.Label7.Text = city.title.Trim();
            this.HyperLink2.Text = city.title.Trim();
            this.HyperLink2.NavigateUrl = "city.aspx?no=" + no;

        }

        this.check_mana_button();


    }

    void check_mana_button()
    {
        if (this.DataList0.Items.Count == 0)
        {
            this.Button7.Visible = false;
        }
        else
        {
            this.Button7.Visible = true;
        }

        if (this.DataList1.Items.Count == 0)
        {
            this.Button8.Visible = false;
        }
        else
        {
            this.Button8.Visible = true;
        }

        if (this.DataList2.Items.Count == 0)
        {
            this.Button9.Visible = false;
        }
        else
        {
            this.Button9.Visible = true;
        }

    }

    void binddata(int i)
    {
        

        if (i == 0)
        {
            var data = from p in db.ct_s_relationships
                       join q in db.ct_s_profiles on p.ct_s_no1 equals q.no
                       where p.ct_s_no2 == no1 && p.type == 1 && q.valid == true && q.language_no == (int)Session["now_user_lang_no"]
                       select new
                       {
                           title = q.title,
                           no = p.ct_s_no1
                       };

            ((DataList)this.Panel1.FindControl("DataList" + i.ToString())).DataSource = data;
            this.Panel1.FindControl("DataList" + i.ToString()).DataBind();

        }
        else
        {

            var data = from p in db.ct_s_relationships
                       join q in db.ct_s_profiles on p.ct_s_no2 equals q.no
                       where p.ct_s_no1 == no1 && p.type == i && q.valid == true && q.language_no == (int)Session["now_user_lang_no"]
                       select new
                       {
                           title = q.title,
                           no = p.ct_s_no2
                       };

            ((DataList)this.Panel1.FindControl("DataList" + i.ToString())).DataSource = data;
            this.Panel1.FindControl("DataList" + i.ToString()).DataBind();

        }
    }

    void bindall()
    {
        for (int i = 0; i < 3; i++)
            binddata(i);

    }


    protected void Button1_Click(object sender, EventArgs e)
    {

        string main_pic_fn = "";
          ct_s_profile oldp=null;

        if (type == 1)
        {

           // var oldp = from p in db.ct_s_profiles
           //            where p.no == no1 && p.language_no==(int)Session["now_user_lang_no"] && p.valid==true
           //            select p;

            oldp = db.ct_s_profiles.Single(p => p.no == no1 && p.language_no == (int)Session["now_user_lang_no"] && p.valid == true);

                oldp.valid = false;
                if (oldp.main_pic_fn != null) main_pic_fn = oldp.main_pic_fn;
            
            db.SubmitChanges();

        }
        
        int newno;
        ct_s_profile c1 = new ct_s_profile();

        if (type == 0)
        {
            //newno = db.ct_s_profiles.Count();
            newno = db.ct_s_profiles.Max(p => p.no)+1;
            c1.ver = 0;

        }
        else
        {
            newno = no1;
            c1.ver = db.ct_s_profiles.Count(p => p.language_no == (int)Session["now_user_lang_no"] && p.no == no1);
            c1.ranking = oldp.ranking;
            c1.ranking_been_there = oldp.ranking_been_there;
            c1.ranking_local = oldp.ranking_local;
            c1.rank_amount = oldp.rank_amount;
            c1.recommend_to_everyone = oldp.recommend_to_everyone;
            c1.recommend_to_first = oldp.recommend_to_first;
            c1.recommend_to_locals = oldp.recommend_to_locals;

        }

        c1.create_user_no = (int)Session["userno"];
        c1.ct_no = no;
        c1.type_no = int.Parse(this.RadioButtonList1.SelectedValue);
        c1.language_no = (int)Session["now_user_lang_no"];
        c1.title = this.TextBox1.Text;
        c1.no = newno;
        c1.profile = this.TextBox2.Text;
        c1.valid = true;
        c1.c_time = DateTime.Now;

        c1.add_time = DateTime.Now;

        if (main_pic_fn != "")
        {
            c1.main_pic_fn = main_pic_fn;
        }
        else
        {
            c1.main_pic_fn = "coming.gif";
        }


        if (this.TextBox3.Text.Trim() != "")
        {
            ct_s_intro i1 = new ct_s_intro();
            i1.ct_s_no = newno;
            i1.create_user_no = (int)Session["userno"];
            i1.intro = this.TextBox3.Text;
            i1.language_no = (int)Session["now_user_lang_no"];
            i1.intro = this.TextBox3.Text;
            i1.ct_no = no;
            db.ct_s_intros.InsertOnSubmit(i1);

            ctp_lib.add_user_city((int)Session["userno"], (int)no);


        }
       
        

        db.ct_s_profiles.InsertOnSubmit(c1);
        db.SubmitChanges();
        
        DatabaseUtil my_util = new DatabaseUtil();
       

        //插入introduction的自動翻譯
        if (this.TextBox3.Text.Trim() != "")
        {
            
            var myidata = from p in db.ct_s_intros
                       where p.create_user_no == (int)Session["userno"]
                       orderby p.addtime descending
                       select p;
            ct_s_intro myi = myidata.First();

            my_util.writeTranslatedTxt((int)DatabaseUtil.fromTables.intro_intro, myi.no, this.TextBox3.Text, "en");



        }


        if (type == 0)
        {
            //插入自動翻譯結果
           // Hashtable lang_table = my_util.getLangTable();
            int translaged_no= my_util.writeTranslatedTxt((int)DatabaseUtil.fromTables.s_profile_title, newno, this.TextBox1.Text, "en");

            //string nickname=db.users.Single(p=>p.no==(int)Session["userno"]).nickname;
            //string descript ="<a href=''>"+ nickname + "</a> 新增了一個景點 - "+this.TextBox1.Text;
            //ctp_lib.insert_news((int)Session["userno"], no, this.TextBox1.Text, (int)ctp_lib.news_type.new_hotspot, newno);


            if (this.ViewState["r_item_0"] != null)
            {
                DataTable dt = (DataTable)this.ViewState["r_item_0"];

                foreach (DataRow r in dt.Rows)
                {
                    ct_s_relationship r1 = new ct_s_relationship();
                    r1.ct_s_no1 = (int)r["no"];
                    r1.ct_s_no2 =newno;
                    r1.user_no = (int)Session["userno"];
                    r1.type = 1;

                    db.ct_s_relationships.InsertOnSubmit(r1);
                    db.SubmitChanges();

                }


            }

            for (int i = 1; i < 3; i++)
            {
                if (this.ViewState["r_item_" + i.ToString()] != null)
                {
                    DataTable dt = (DataTable)this.ViewState["r_item_" + i.ToString()];

                    foreach (DataRow r in dt.Rows)
                    {
                        ct_s_relationship r1 = new ct_s_relationship();
                        r1.ct_s_no1 = newno;
                        r1.ct_s_no2 = (int)r["no"];
                        r1.user_no = (int)Session["userno"];
                        r1.type = i;

                        db.ct_s_relationships.InsertOnSubmit(r1);
                        db.SubmitChanges();

                    }


                }
            }

          //  Response.Redirect("city.aspx?no=" + no.ToString());


        }
        else if (type == 1) //edit hotspot
        {
             //init helper class
            GeoLingManager glManager = new GeoLingManager(Request, Response);
            String _lang = glManager.getLang();
            //Get user's preferred langugage in int
            _lang = my_util.getLanguageNo(_lang).ToString();
            my_util.writeTranslatedTextToHistory((int)DatabaseUtil.fromTables.s_profile_title, c1.no, c1.title, DataUtil.StringToInt(_lang));
        }
        else
        {

            //  Response.Redirect("city_s.aspx?no=" + no1.ToString());



        }


        Response.Redirect("city_s.aspx?no=" + newno.ToString());


    }
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        //int type_no = int.Parse(this.RadioButtonList1.SelectedValue);

        //var type1 = from p in db.ct_s_type1s
        //            where p.language_no == (int)Session["now_user_lang_no"] && p.type_no == type_no
        //            select p;

        //this.RadioButtonList2.DataSource=type1;
        //this.RadioButtonList2.DataBind();
    }
    
    protected void Button4_Click(object sender, EventArgs e)
    {
        select_items();

        this.ViewState["r_type"] = 0;

    }

    private void select_items()
    {
        this.Panel1.Visible = false;
        this.Panel2.Visible = true;

        ctpDataContext db = new ctpDataContext();
        var items = from p in db.ct_s_profiles
                    where p.ct_no == no && p.valid==true
                    select p;

        this.CheckBoxList1.DataSource = items;
        this.CheckBoxList1.DataBind();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

        int thistype = (int)this.ViewState["r_type"];

        DataTable dt;

        if (type == 0)
        {

            if (ViewState["r_item_" + (thistype % 3).ToString()] == null)
            {
                dt = new DataTable();
                dt.Columns.Add("title", typeof(string));
                dt.Columns.Add("no", typeof(int));
                dt.PrimaryKey = new DataColumn[] { dt.Columns["no"] };
            }
            else
            {
                dt = (DataTable)this.ViewState["r_item_" + (thistype % 3).ToString()];

            }

            foreach (ListItem i in this.CheckBoxList1.Items)
            {
                if (i.Selected)
                {
                   
                        if (thistype < 3)
                        {
                            dt.Rows.Add(i.Text, int.Parse(i.Value));

                        }
                  
                }
                else
                {
                    
                        if (thistype > 2)
                        {
                            DataRow r = dt.Rows.Find(int.Parse(i.Value));
                            dt.Rows.Remove(r);
                        }
                    

                }
            }

            ((DataList)this.Panel1.FindControl("DataList" + (thistype % 3).ToString())).DataSource = dt;
            ((DataList)this.Panel1.FindControl("DataList" + (thistype % 3).ToString())).DataBind();

            this.ViewState["r_item_" + thistype.ToString()] = dt;


        }
        else
        {
            foreach (ListItem i in this.CheckBoxList1.Items)
            {
                if (i.Selected)
                {
                    if (thistype < 3)
                    {
                        ct_s_relationship r1 = new ct_s_relationship();


                        if (thistype == 0)
                        {
                            r1.ct_s_no1 = int.Parse(i.Value);
                            r1.ct_s_no2 = no1;
                            r1.user_no = (int)Session["userno"];
                            r1.type = 1;
  
                        }
                        else
                        {
                            r1.ct_s_no1 = no1;
                            r1.ct_s_no2 = int.Parse(i.Value);
                            r1.user_no = (int)Session["userno"];
                            r1.type = (int)this.ViewState["r_type"];
                        }
                        db.ct_s_relationships.InsertOnSubmit(r1);
                        db.SubmitChanges();
                    }
                }
                else
                {
                    if (thistype >2)
                    {
                        if (thistype == 3)
                        {
                            var data = from p in db.ct_s_relationships
                                       where p.ct_s_no1 ==int.Parse(i.Value) && p.ct_s_no2 ==no1 && p.type == 1
                                       select p;

                            db.ct_s_relationships.DeleteAllOnSubmit(data);
                            db.SubmitChanges();
                        }
                        else
                        {
                            var data = from p in db.ct_s_relationships
                                       where p.ct_s_no1 == no1 && p.ct_s_no2 == int.Parse(i.Value) && p.type == thistype % 3
                                       select p;

                            db.ct_s_relationships.DeleteAllOnSubmit(data);
                            db.SubmitChanges();
                        }

                    }
                }
            }

            this.binddata(thistype%3);

        }


        this.check_mana_button();

        this.Panel1.Visible = true;
        this.Panel2.Visible = false;

    }
    protected void Button3_Click(object sender, EventArgs e)
    {

        this.Panel1.Visible = true;
        this.Panel2.Visible = false;

    }
    protected void Button5_Click(object sender, EventArgs e)
    {

        this.select_items();
        this.ViewState["r_type"] = 1;

    }
    protected void Button6_Click(object sender, EventArgs e)
    {
        this.select_items();
        this.ViewState["r_type"] = 2;
    }
    protected void Button7_Click(object sender, EventArgs e)
    {

        this.ViewState["r_type"] = 3;

        this.mana_items();


    }

    void mana_items()
    {
        int thistype = (int)this.ViewState["r_type"];

        if (type == 0)
        {

            this.CheckBoxList1.DataSource = (DataTable)this.ViewState["r_item_" + (thistype % 3).ToString()];

        }
        else
        {

            if (thistype%3 == 0)
            {
                var data = from p in db.ct_s_relationships
                           join q in db.ct_s_profiles on p.ct_s_no1 equals q.no
                           where p.ct_s_no2 == no1 && p.type == 1 && q.valid == true && q.language_no == (int)Session["now_user_lang_no"]
                           select new
                           {
                               title = q.title,
                               no = p.ct_s_no1
                           };

                this.CheckBoxList1.DataSource = data;

            }
            else
            {

                var data = from p in db.ct_s_relationships
                           join q in db.ct_s_profiles on p.ct_s_no2 equals q.no
                           where p.ct_s_no1 == no1 && p.type == thistype%3 && q.valid == true && q.language_no == (int)Session["now_user_lang_no"]
                           select new
                           {
                               title = q.title,
                               no = p.ct_s_no2
                           };

                this.CheckBoxList1.DataSource = data;

            }



            //var data = from p in db.ct_s_relationships
            //           join q in db.ct_s_profiles on p.ct_s_no2 equals q.no
            //           where p.ct_s_no1 == no1 && p.type == thistype%3
            //           select new
            //           {
            //               title = q.title,
            //               no = p.ct_s_no2
            //           };


        }

        this.CheckBoxList1.DataBind();


        foreach (ListItem i in this.CheckBoxList1.Items)
        {
            i.Selected = true;
        }

        this.Panel1.Visible = false;
        this.Panel2.Visible = true;

    }
    protected void Button8_Click(object sender, EventArgs e)
    {
        this.ViewState["r_type"] = 4;

        this.mana_items();

    }
    protected void Button9_Click(object sender, EventArgs e)
    {
        this.ViewState["r_type"] = 5;

        this.mana_items();

    }
    protected void TextBox3_TextChanged(object sender, EventArgs e)
    {

    }
}
